/*数据库操作*/
/*http请求*/
const rp = require('request-promise');
/*登录信息校验*/
const tokenvilidate = require('../../common/tokenvilidate.js');
/*数据库工具*/
const basics_db = require('../../dbhelper/basics_db.js');
/*淘宝客工具*/
const tbkUtil = require('../../../utils/tbk_util.js');
/*通用工具*/
const jason_tools = require('../../../utils/jason_tools.js');

/*根参数*/
const appkey = '28243418';
const appsecret = '8acfffd32b0f66ebaae5863ef57ab771';
const pid = 'mm_113916518_1166900193_110146300461';
/* 淘宝官方 */
const uri = 'http://gw.api.taobao.com/router/rest';
/* 维易淘宝客API */
const WYzluri = 'http://api.vephp.com/hcapi';
const WYsuper = 'http://apis.vephp.com/super';
const WYOrderuri = 'http://apiorder.vephp.com/order';
const WYTbcats = 'http://api.vephp.com/tbcats';
const WYvekey = 'V00001109Y18343095';

/**
 * 查询主名称
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getSHname = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.query;

    let data = await basics_db.findOne('user', { "aliasId": query.aliasId })
    let name;

    if (data) {
        name = data.name.charAt(data.name.length - 1)
    } else {
        name = '主'
    }

    return ctx.body = { 'name': name };
}

/**
 * 登录用户信息
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getUserInfo = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;
    if (!query.phone || !query.password) {
        return ctx.body = {
            ok: 0,
            message: '已经触发警报！！'
        };
    }
    let phone = query.phone + '';
    let data = await basics_db.findOne('user', { "phone": phone })

    if (!data) {
        return ctx.body = {
            ok: 0,
            message: '用户名不存在！'
        };
    }
    if (data.password == query.password) {
        let dataObj = {
            aliasId: data.aliasId,
            name: data.name,
            phone: data.phone,
            token: data._id
        }
        return ctx.body = {
            ok: 1,
            data: dataObj
        };
    } else {
        return ctx.body = {
            ok: 0,
            message: '用户名或密码错误！'
        };
    }
}

/**
 * 订单查询excel接口
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getTkOrder = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;
    let tokens = ctx.request.header.token;
    /*检验身份*/
    let tokenRes = await tokenvilidate.tokenCheck(tokens);
    if (!tokenRes.ok) {
        return ctx.body = tokenRes
    }

    let orders = await basics_db.find('order', { 'pid': tokenRes.data.myId.split('_')[3] })
    let txOrders = await basics_db.find('txmoney', { "objId": tokenRes.data._id + '' })

    let txOrdersStr = '';
    for (let item in txOrders) {
        txOrdersStr = txOrdersStr + txOrders[item].txOrders + ','
    }

    // 除去已经体现实际存在订单
    let actualOrders = [];
    if (orders && orders.length) {
        for (let item in orders) {
            if (txOrdersStr.indexOf(orders[item].trade_id) == -1) {
                actualOrders.push(orders[item])
            }
        }
    }

    let validOrders = 0;
    let estimate_m = 0;
    let settlement_m = 0;

    if (actualOrders && actualOrders.length) {
        for (let item in actualOrders) {
            // 回扣处理
            if (tokenRes.data.aliasId.indexOf('A') < 0) {
                actualOrders[item].estimate_m = Math.floor((actualOrders[item].estimate_m * 0.7) * 100) / 100;
            }
            // 有效订单
            if (actualOrders[item].state != '订单失效') {
                validOrders += 1;
                estimate_m += actualOrders[item].estimate_m;
            }
            // 结算订单
            if (actualOrders[item].state == '订单结算') {
                settlement_m += actualOrders[item].estimate_m
            }

        }
    } else {
        return ctx.body = {
            ok: 0,
            orderList: [],
            message: '您还没有订单，请努力！'
        };
    }

    return ctx.body = {
        ok: 1,
        orderList: actualOrders,
        alloOrders: actualOrders.length,
        validOrders: validOrders,
        estimate_m: estimate_m.toFixed(2),
        settlement_m: settlement_m.toFixed(2)
    };
}

/**
 * 粉丝订单查询excel接口
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getFSOrder = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;
    let tokens = ctx.request.header.token;
    /*检验身份*/
    let tokenRes = await tokenvilidate.tokenCheck(tokens);
    if (!tokenRes.ok) {
        return ctx.body = tokenRes
    }

    let ziFsUser = await basics_db.find('user', { 'byAlias': tokenRes.data.aliasId })

    let orders = [];
    if (ziFsUser && ziFsUser.length) {
        for (let index = 0; index < ziFsUser.length; index++) {
            let os = await basics_db.find('order', { 'pid': ziFsUser[index].myId.split('_')[3] })
            orders = orders.concat(os);
        }
    }


    let txOrders = await basics_db.find('txmoney', { "objId": tokenRes.data._id + '' })

    let txOrdersStr = '';
    for (let item in txOrders) {
        txOrdersStr = txOrdersStr + txOrders[item].txOrders + ','
    }

    // 除去已经体现实际存在订单
    let actualOrders = [];
    if (orders && orders.length) {
        for (let item in orders) {
            if (txOrdersStr.indexOf(orders[item].trade_id) == -1) {
                actualOrders.push(orders[item])
            }
        }
    }

    let validOrders = 0;
    let estimate_m = 0;
    let settlement_m = 0;

    if (actualOrders && actualOrders.length) {
        for (let item in actualOrders) {
            // 回扣处理
            actualOrders[item].estimate_m = Math.floor((actualOrders[item].estimate_m * 0.1) * 100) / 100;
            actualOrders[item].platformName = actualOrders[item].platformName.substr(actualOrders[item].platformName.length - 1, 1)

            // 有效订单
            if (actualOrders[item].state != '订单失效') {
                validOrders += 1;
                estimate_m += actualOrders[item].estimate_m;
            }
            // 结算订单
            if (actualOrders[item].state == '订单结算') {
                settlement_m += actualOrders[item].estimate_m
            }

        }
    } else {
        return ctx.body = {
            ok: 0,
            orderList: [],
            message: '您还没有粉丝的返利订单！'
        };
    }

    return ctx.body = {
        ok: 1,
        orderList: actualOrders,
        alloOrders: actualOrders.length,
        validOrders: validOrders,
        estimate_m: estimate_m.toFixed(2),
        settlement_m: settlement_m.toFixed(2)
    };
}

/**
 * 查看全部资产返利
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getAllOrderMoney = async (ctx, next) => {
}




/**
 * 查询订单（淘宝客数据订单 -- 分时查询）
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.scOrderGet = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;
    let tokens = ctx.request.header.token;
    /*检验身份*/
    let tokenRes = await tokenvilidate.tokenCheck(tokens);
    if (!tokenRes.ok) {
        return ctx.body = tokenRes
    }

    /*传参声明*/
    // let sessionData = await basics_db.findOne('system',{'name': 'sessionKey'})
    // let params = {
    //     app_key: appkey,
    //     sign_method: 'md5',
    //     format: 'json',
    //     v: '2.0',
    //     timestamp: tbkUtil.YYYYMMDDHHmmss(),
    //     session: sessionData.access_token,
    //     method: 'taobao.tbk.sc.order.get',
    //     fields: 'tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,relation_id,tb_trade_parent_id,tb_trade_id,num_iid,item_title,item_num,price,pay_price,seller_nick,seller_shop_title,commission,commission_rate,unid,create_time,earning_time,tk3rd_pub_id,tk3rd_site_id,tk3rd_adzone_id,special_id,click_time',
    //     start_time: start_time
    // };
    // Object.assign(params, query);
    // /*签名*/
    // params.sign = sign(params);

    /*传参声明*/
    let startTime = jason_tools.formatDate(query.start_time, 'yyyy-MM-dd hh:mm:ss');
    let params = {
        vekey: WYvekey,
        start_time: startTime,
        tk_status: '1'
    };
    /*函数体*/
    let options = {
        uri: WYOrderuri,
        qs: params,
        headers: {
            'User-Agent': 'Request-Promise',
        },
        json: true // Automatically parses the JSON string in the response
    };
    /*请求体*/
    let res;
    await rp(options)
        .then(function (repos) {
            res = [];
            for (const key in repos.data) {
                if (repos.data[key].adzone_id == tokenRes.data.myId.split('_')[3]) {
                    // 回扣处理
                    if (tokenRes.data.aliasId.indexOf('A') < 0) {
                        repos.data[key].pub_share_pre_fee = Math.floor((repos.data[key].pub_share_pre_fee * 0.7) * 100) / 100;
                    }

                    if (repos.data[key].tk_status == 3) {
                        repos.data[key].tk_status = '订单结算'
                    } else if (repos.data[key].tk_status == 12) {
                        repos.data[key].tk_status = '订单付款'
                    } else if (repos.data[key].tk_status == 13) {
                        repos.data[key].tk_status = '订单失效'
                    } else if (repos.data[key].tk_status == 14) {
                        repos.data[key].tk_status = '订单成功'
                    }

                    repos.data[key].total_commission_rate = (repos.data[key].total_commission_rate * 100).toFixed(2);
                    res.push(repos.data[key])
                }
            }
        })
        .catch(function (err) {
            return ctx.body = {
                ok: 0,
                message: err
            };
        });

    return ctx.body = {
        ok: 1,
        orderList: res
    };
}

/**
 * 资产转化提交
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.orderTransTx = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;
    let tokens = ctx.request.header.token;
    /*检验身份*/
    let tokenRes = await tokenvilidate.tokenCheck(tokens);
    if (!tokenRes.ok) {
        return ctx.body = tokenRes
    }

    let baseData = {
        "objId": tokenRes.data._id + '',
        "phone": tokenRes.data.phone,
        "xtDate": jason_tools.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        "txMoney": query.money,
        "txOrders": query.orders,
        "txModel": "",
        "modelOders": "",
        "remarks": "备注",
        "states": 0
    }

    let insert = await basics_db.insert('txmoney', baseData)

    return ctx.body = insert;
}


/**
 * 资产转化记录
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.orderTransHistory = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;
    let tokens = ctx.request.header.token;
    /*检验身份*/
    let tokenRes = await tokenvilidate.tokenCheck(tokens);
    if (!tokenRes.ok) {
        return ctx.body = tokenRes
    }

    let find = await basics_db.find('txmoney', { "objId": tokenRes.data._id + '' })

    return ctx.body = {
        ok: 1,
        historyList: find
    };
}

/**
 * 代理申请提交
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.applyDl = async (ctx, next) => {
    /*参数声明*/
    let query = ctx.request.body;

    let baseData = query

    let insert = await basics_db.insert('apply', baseData)

    return ctx.body = insert;
}

/**
 * 淘宝二级分类
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.getTbcats = async (ctx, next) => {

    let data = await basics_db.find('cats', {})

    return ctx.body = data;
}

/**
 * 数据通讯测试
 * @author jaosnZhang
 * @param {Object} ctx 响应主体文本
 * @param {Function} next 异步函数跳返
 * @return {Object} ctx.body 返回信息对象
 */
exports.dataTest = async (ctx, next) => {
    /*数据操作*/
    let data = await basics_db.findOne('user', { 'name': '张海芳' })
    return ctx.body = data;
}
